package com.ycsj.goldmedalnewconcept.common.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.iflytek.cloud.SpeechUtility;
import com.makeramen.roundedimageview.RoundedImageView;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam;
import com.permissionx.guolindev.callback.ForwardToSettingsCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;
import com.permissionx.guolindev.request.ForwardScope;
import com.wang.avi.AVLoadingIndicatorView;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.bean.WordPreInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.iflytek.Result;
import com.ycsj.goldmedalnewconcept.common.iflytek.XmlResultParser;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;
import okhttp3.Call;

/**
 * 单词预习的Fragment
 * Created by Administrator on 2019/4/3 0003.
 */

public class WordsYxFragment extends BaseLazyFragment implements CancelAdapt {

    @BindView(R.id.iv_pic)
    RoundedImageView ivPic;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    @BindView(R.id.tv_yin)
    TextView tvYin;
    @BindView(R.id.lv_play)
    ImageView lvPlay;
    @BindView(R.id.ll_yin)
    LinearLayout llYin;
    @BindView(R.id.tv_yi)
    TextView tvYi;
//    @BindView(R.id.tv_ci)
//    TextView tvCi;

    @BindView(R.id.ll_yi)
    LinearLayout llYi;
    @BindView(R.id.tv_li)
    TextView tvLi;
    @BindView(R.id.ll_li)
    LinearLayout llLi;
    @BindView(R.id.lv_play_record)
    ImageView lvPlayRecord;
    @BindView(R.id.lv_record)
    ImageView lvRecord;
    @BindView(R.id.avind)
    AVLoadingIndicatorView avind;
    @BindView(R.id.ll_loading)
    LinearLayout llLoading;
    @BindView(R.id.tv_score)
    TextView tvScore;
    @BindView(R.id.ll_botttom)
    LinearLayout llBotttom;

    //播放器停止播放的标识
    public static final int STOPPLAY = 0x660;

    //页面对象
    private WordPreInfo.QuestionListBean info;

    //位置
    private int pos;

    //收藏接口需要的lessonId
    private String lessionId;

    //单词的播放动画对象
    private AnimationDrawable wordAnim;
    private List<WordPreInfo.QuestionListBean.DetailListBean> datas;

    // 控制松手是否显示加载框的标记
    private boolean isShowDialog = true;

    // 用于控制第一次点击播放状态,默认是没有录音文件的
    private boolean hasRecord = false;

    //讯飞SDK对象
    private SpeechEvaluator mSpeechEvaluator;

    //控制录音次数
    private int recordCount;

    /**
     * 录音的弹框PopUpWinow相关
     */
    private View view;
    private ImageView lvPopRecord;
    private PopupWindow popupWindow;
    //录音对话框的帧动画对象
    private AnimationDrawable popAnimationDrawable;


    //录音权限
    private String[] permissions = {Manifest.permission.RECORD_AUDIO,};


    //是否按下了
    private boolean hasActionDown = false;

    /**
     * 创建当前页面的方法
     *
     * @param info      页面的问题对象
     * @param pos       问题所在的位置
     * @param lessionId lessionId
     * @return
     */
    public static WordsYxFragment newInstance(WordPreInfo.QuestionListBean info, int pos,
                                              String lessionId) {
        WordsYxFragment wordsYxFragment = new WordsYxFragment();

        // 通过arguments携带页面数据
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putInt("position", pos);
        bundle.putString("lessionId", lessionId);
        wordsYxFragment.setArguments(bundle);
        return wordsYxFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_words_yx;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //获取传递数据
        initIntent();

        //初始化状态
        initState();

        // 配置讯飞SDK对象的参数
        setParams();

        //初始化录制音频按钮的触摸事件
        initRecrdTouchEvent();
    }

    /**
     * 获取传递数据
     */
    private void initIntent() {
        info = (WordPreInfo.QuestionListBean) getArguments().getSerializable("data");
        pos = getArguments().getInt("position");
        lessionId = getArguments().getString("lessionId");
    }

    /**
     * 设置讯飞语音录制对象的参数方法
     */
    private void setParams() {

//        LogUtils.iTag("test", "上下文对象是" + getContext());


        mSpeechEvaluator = SpeechEvaluator.createEvaluator(getContext(), null);

//        LogUtils.iTag("test", "测评对象是" + mSpeechEvaluator);

        // 设置评测语种
        mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");

        // 设置评测题型
        mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY, "read_word");

        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
        // "read_sentence");// 句子

        // 设置试题编码类型
        mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");

        // 设置前、后端点超时
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "5000");

        mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");

        // 设置录音超时，设置成-1 则无超时限制
        mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");

        // 设置结果等级，不同等级对应不同的详细程度
        mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

    }


    // 检查是否已授权
    private boolean checkPermission(String permissionName) {
        return PermissionX.isGranted(getContext(), permissionName);
    }


    //申请权限
    private void applyPermission() {

        PermissionX.init(this)
                .permissions(permissions)
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {
//                            LogUtils.iTag("test", "申请权限了");
                        } else {
//                            LogUtils.iTag("test", "拒绝权限了");
                            Toast.makeText(getActivity(), "录音权限未通过，录音功能无法使用", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 初始化录制音频按钮的触摸事件
     */
    private void initRecrdTouchEvent() {

        lvRecord.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:

//                        if (recordCount < 2) {
//                            // 按下的时候重置状态
//                            isShowDialog = true;
//
//                            // 隐藏加载显示分数,下一步按钮
//                            llLoading.setVisibility(View.INVISIBLE);
//                            tvScore.setVisibility(View.INVISIBLE);
//
//                            // 按下的操作
//                            showRecordPop();
//
//                            // 同时开始录音并播放
//                            doRecordAction();
//                        } else {
//                           ToastUtils.showShort("最多只能进行2次评测");
//                        }


                        //先进行权限的判定,如果没有权限就去申请权限,有权限在进行录音操作
                        if (checkPermission(Manifest.permission.RECORD_AUDIO)) {
                            if (recordCount < 2) {
                                // 按下的时候重置状态
                                isShowDialog = true;

                                // 隐藏加载显示分数,下一步按钮
                                llLoading.setVisibility(View.INVISIBLE);
                                tvScore.setVisibility(View.INVISIBLE);

                                // 按下的操作
                                showRecordPop();

                                // 同时开始录音并播放
                                doRecordAction();


                                //是否按下了
                                hasActionDown = true;


                            } else {
                                ToastUtils.showShort("最多只能进行2次评测");
                            }
                        } else {
                            //没有录音权限,申请录音权限
                            applyPermission();
                        }

                        break;

                    case MotionEvent.ACTION_UP:

                        // 停止评测方法
//                        if (null != mSpeechEvaluator) {
//                            mSpeechEvaluator.stopEvaluating();
//                        }

                        if (hasActionDown) {
                            // 松下的操作
                            if (null != popupWindow && popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }


                            // 松手的时候开始加载框转圈功能
                            if (null != llLoading) {
                                if (isShowDialog) {
                                    llLoading.setVisibility(View.VISIBLE);
                                } else {
                                    llLoading.setVisibility(View.INVISIBLE);
                                }
                            }

                            //还原按下状态
                            hasActionDown = false;
                        }
                }

                return true;
            }
        });
    }

    /**
     * 初始化状态
     */
    private void initState() {
        //初始化状态下
        tvYi.setVisibility(View.INVISIBLE);
        tvLi.setVisibility(View.INVISIBLE);

        if (null != info) {
            //设置数据
            //图像取第1个元素
            datas = info.getDetail_list();
            if (null != datas && datas.size() != 0) {

                ImageUtil.displayImage(getContext(), ivPic, datas.get(1).getDetail_content(), R.drawable.ic_default_image);


                // 设置词,getQuestion_content
//                tvCi.setText(info.getQuestion_content());

                // 设置音,取集合的第三个元素
                tvYin.setText(datas.get(3).getDetail_content());

                // 设置译,取集合的第第二个元素
                tvYi.setText(datas.get(2).getDetail_content());

                // 设置例
                tvLi.setText(datas.get(4).getDetail_content());

                // 设置是否已经收藏的图标
                if ("1".equals(info.getFavor_status())) {
                    // 表示收藏过
                    ivCollect.setImageResource(R.drawable.collection_select);
                } else {
                    // 表示没有收藏
                    ivCollect.setImageResource(R.drawable.collection_nomal);
                }
            }
        }
    }

    /**
     * 收藏和取消收藏的接口
     * exam_type  要按  1：词汇检测  2：预习检测  3：词汇预习  4：语法检测  5：微课堂  6：题库练习  9：跟读
     */
    private void httpCollection() {

        CustomDialogManager.show(getContext(), "执行中...");

        Map<String, String> map = new HashMap<>();
        String url = "";
        if ("1".equals(info.getFavor_status())) {
            // 表示已经收藏过,请求取消收藏接口
            url = HttpAddress.CANCELCOLLECTION;
            map.put("type", "16");
        } else {
            // 表示没有收藏过,请求收藏接口
            url = HttpAddress.COLLECITON;
            map.put("type", "15");
        }

        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("lessonid", lessionId);
        map.put("questionid", info.getQuestion_id());
        map.put("exam_type", "3");
        map.put("apptoken", AccountUtils.getToken(getContext()));
        map.put("platform", "2");

        HttpUtils.get(url, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo res = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        res = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        LogUtils.iTag("test", Constants.PARSEDATAERROR);
                    }

                    if (null != res) {
                        if ("200".equals(res.getState())) {
                            if ("1".equals(info.getFavor_status())) {
                                // 取消收藏成功
                                info.setFavor_status("0");
                                ivCollect.setImageResource(R.drawable.collection_nomal);
                                ToastUtils.showShort("取消成功");
                            } else {
                                // 收藏成功
                                info.setFavor_status("1");
                                ivCollect.setImageResource(R.drawable.collection_select);
                                ToastUtils.showShort("收藏成功");
                            }
                        } else {
                            ToastUtils.showShort("操作失败,异常码是:" + res.getState());
                        }
                    }
                }
            }
        });
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.rl_collect, R.id.lv_play, R.id.lv_play_record, R.id.lv_yi, R.id.lv_li})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_collect:
                //收藏
                httpCollection();
                break;
            case R.id.lv_play_record:
                //播放录音
                doRecordAudio();
                break;
            case R.id.lv_play:
                //播放单词的音频
                doPlayWordAudio();
                break;
            case R.id.lv_yi:
                //译
                sysVisableState();
                break;
            case R.id.lv_li:
                //例
                sysVisableState();
                break;
        }
    }

    /**
     * 播放单词音频
     */
    private void doPlayWordAudio() {

        wordAnim = (AnimationDrawable) lvPlay.getDrawable();

        //还原播放录音按钮的状态
        lvPlayRecord.setImageResource(R.drawable.playcloze);

        //播放音频
        MediaPlayerManager.getInstance().play(datas.get(0).getDetail_content(), new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                //开启动画
                wordAnim.start();
            }
        }, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                //播放完成
                wordAnim.stop();
                wordAnim = null;
                lvPlay.setImageResource(R.drawable.st_voice_anim);
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                //播放出错
                wordAnim.stop();
                wordAnim = null;
                lvPlay.setImageResource(R.drawable.st_voice_anim);
                return false;
            }
        });
    }

    /**
     * 同步译和例显示的方法
     */
    private void sysVisableState() {
        if (tvYi.getVisibility() != View.VISIBLE && tvLi.getVisibility() != View.VISIBLE) {
            tvYi.setVisibility(View.VISIBLE);
            tvLi.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 弹出录音的PopUpwindow
     */
    private void showRecordPop() {

        view = View.inflate(getContext(), R.layout.st_pop_record, null);

        lvPopRecord = view.findViewById(R.id.lv_pop_record);

        // 给顶部的图片设置帧动画
        lvPopRecord.setImageResource(R.drawable.st_record_anim);

        // 获取帧动画对象
        popAnimationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

        // 开启帧动画
        popAnimationDrawable.start();

        popupWindow = new PopupWindow(view,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (null != popAnimationDrawable) {
                    popAnimationDrawable.stop();
                }
            }
        });

        popupWindow.showAtLocation(this.getActivity().getWindow().getDecorView(),
                Gravity.CENTER, 0, 0);

    }

    /**
     * 语音评测的方法
     */
    @SuppressLint("MissingPermission")
    private void doRecordAction() {

        //记录录音的次数
//        recordCount++;

        // 清空播放器的播放状态
        MediaPlayerManager.getInstance().stop();

        // 清除播放单词的录音
        if (wordAnim != null) {
            wordAnim.stop();
            lvPlay.setImageResource(R.drawable.st_voice_anim);
        }

        // 恢复底部的播放按钮的状态
        lvPlayRecord.setImageResource(R.drawable.playcloze);

        // 震动手机
        Vibrator vibrator = (Vibrator) getActivity().getSystemService(
                Service.VIBRATOR_SERVICE);
        vibrator.vibrate(500);

        if (mSpeechEvaluator == null) {
            return;
        }

        // 重新配置讯飞的录音存放位置
        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
                getActivity().getExternalCacheDir().getAbsolutePath()
                        + "/msc/" + "icewordsyx" + lessionId + pos + ".wav");

        //开启评测
        mSpeechEvaluator.startEvaluating("[word]\r\n" + info.getQuestion_content(), null, new EvaluatorListener() {
            // volume音量值0~30，data音频数据
            @Override
            public void onVolumeChanged(int volume, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {

            }

            @Override
            public void onEndOfSpeech() {

            }

            // 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
            @Override
            public void onResult(EvaluatorResult result, boolean isLast) {

                if (isLast) {

                    StringBuilder builder = new StringBuilder();
                    builder.append(result.getResultString());

                    XmlResultParser resultParser = new XmlResultParser();
                    Result result1 = resultParser.parse(result
                            .getResultString());


                    // 处理乱读的问题
                    if (!TextUtils.isEmpty(builder)) {
                        //通过分数来判断是否是乱读
                        //取出评测的分数
                        float a = result1.total_score;
                        float b = (float) (Math.round(a * 10)) / 10;
//                        if (!result1.is_rejected) {
                        if (b != 0.0) {
                            // 更改是否继续显示弹框的标识
                            isShowDialog = false;

                            // 松下的操作
                            closeRecordPop();

                            llLoading.setVisibility(View.INVISIBLE);
                            tvScore.setVisibility(View.VISIBLE);
                            tvScore.setText(b + " 分");

                            // 播放科大讯飞的评分语音
                            int resId = -1;
                            if (b < 1.0) {
                                resId = R.raw.musicrecord1;
                            } else if (b >= 1.0 && b < 2.0) {
                                resId = R.raw.musicrecord2;
                            } else if (b >= 2.0 && b < 3.0) {
                                resId = R.raw.musicrecord3;
                            } else if (b >= 3.0 && b < 4.0) {
                                resId = R.raw.musicrecord4;
                            } else if (b >= 4.0 && b <= 5.0) {
                                resId = R.raw.musicrecord5;
                            }

                            MediaPlayerManager.getInstance().playLocalFile(resId, null, null);

                        } else {
                            //乱读或未读
                            isShowDialog = false;

                            // 更改录音文件状态证明已经录音
                            hasRecord = false;

                            closeRecordPop();

                            llLoading.setVisibility(View.INVISIBLE);
                            tvScore.setVisibility(View.VISIBLE);
                            tvScore.setText("0.0 分");

                            ToastUtils.showShort("未检测到录音或者乱读,请重新录音");
                        }
                    }
                }
            }

            @Override
            public void onError(SpeechError error) {

                // 更新是否显示PopUpWindow
                isShowDialog = false;

                closeRecordPop();

                if (null != llLoading) {
                    llLoading.setVisibility(View.INVISIBLE);
                }

                if (null != tvScore) {
                    tvScore.setVisibility(View.INVISIBLE);
                }

                ToastUtils.showShort("请重新录音");

                Log.d("test", error.getErrorCode() + "");
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });

    }

    /**
     * 播放录音文件
     */
    private void doRecordAudio() {
        // 获取录音文件的地址
        if (!TextUtils.isEmpty(getAmrPath(pos))) {

            // 停止播放单词的动画
            if (wordAnim != null && wordAnim.isRunning()) {
                wordAnim.stop();
                lvPlay.setImageResource(R.drawable.st_voice_anim);
            }

            lvPlayRecord.setImageResource(R.drawable.stopcloze);

            //播放当前录制的音频
            MediaPlayerManager.getInstance().play(getAmrPath(pos), new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    lvPlayRecord.setImageResource(R.drawable.playcloze);
                }
            }, null);

        } else {
            // 无存放的音频文件
            ToastUtils.showShort("请先录音");
        }
    }

    /**
     * 根据当前页面获取录音文件的路径的方法
     *
     * @return
     */
    private String getAmrPath(int pos) {
//        LogUtils.iTag("test", "当前位置是:", pos);

//        String filePath = getActivity().getExternalCacheDir().getAbsolutePath()
//                + "/msc/"
//                + "icewordsyx"
//                + lessionId
//                + pos
//                + ".wav";
//        LogUtils.iTag("录音文件的存放位置是:", getActivity().getExternalCacheDir().getAbsolutePath());

//        LogUtils.iTag("test", "存储位置是:", filePath);
        File file = new File(
                getActivity().getExternalCacheDir().getAbsolutePath()
                        + "/msc/"
                        + "icewordsyx"
                        + lessionId
                        + pos
                        + ".wav");
        if (file.exists()) {
            return file.getAbsolutePath();
        } else {
            return "";
        }
    }

    /**
     * 关闭录音弹框的方法
     */
    private void closeRecordPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && STOPPLAY == busInfo.type) {
            MediaPlayerManager.getInstance().stop();

            //恢复单词播放的状态
            lvPlay.setImageResource(R.drawable.st_voice_anim);

            //恢复录音播放的状态
            lvPlayRecord.setImageResource(R.drawable.playcloze);
        }
        super.busEvent(busInfo);
    }

    @Override
    public void onDestroy() {
        //清空播放器
        MediaPlayerManager.getInstance().stop();
        super.onDestroy();
    }
}
